package com.gzz.boot.repush;

import com.alibaba.fastjson.JSON;
import com.gzz.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 重推实现类
 *
 */
@Service
@Slf4j
public class RePushServiceImpl implements IRePushService {

    @Resource
    private RePushMapper rePushMapper;

    /**
     * 推送状态(已推送)
     */
    public static final Integer STATUS_SUCCESS = 1;
    /**
     * 推送状态(未推送)
     */
    public static final Integer STATUS_FAILURE = 0;

    /**
     * 分隔符
     */
    public static final String DELIMITER = ",";

    /**
     * 最大重推次数
     */
    public static final Integer MAX_RE_PUSH_NUM = 3;

    @Override
    public List<RePush> queryRePushData() {
//        Example example = Example.builder(RePush.class).build();
//        example.createCriteria().andEqualTo("status",STATUS_FAILURE).orLessThanOrEqualTo("pushNum",MAX_RE_PUSH_NUM);
//
//        return rePushMapper.selectByExample(example);
        return null;
    }

    /**
     * 记录重推参数
     * @param interfaceName 接口名称
     * @param status 推送状态 0:未推送  1:已推送 (默认成功)
     * @param callbackMethod 回调方法
     * @param className 类名 Class.getName()
     * @param methodName 方法名
     * @param params 方法参数
     */
    @Override
    public void saveReRushLog(String interfaceName,Integer status ,Predicate<Object> callbackMethod,String className, String methodName,Object... params) throws Exception{
        // 参数校验
        Assert.notNull(interfaceName,"接口名称不能为空!");
        Assert.notNull(className,"类名不能为空!");
        Assert.notNull(methodName,"方法名不能为空!");

        status = Optional.ofNullable(status).orElse(STATUS_SUCCESS);

        // 校验类名
        Class<?> aClass ;
        try {
            aClass = Class.forName(className);
        } catch (Exception e) {
            throw new RuntimeException("未找到类名:"+className);
        }

        // 校验方法名+参数
        try {
            if(null != params){
                List<Class<?>> classList = Arrays.stream(params).map(Object::getClass).collect(Collectors.toList());
                int size = classList.size();
                Class<?> [] aClassList = new Class[size];
                for(int i=0;i<size;i++){
                    aClassList[i] = classList.get(i);
                }
                Method method = aClass.getMethod(methodName, aClassList);
                Assert.notNull(method,String.format("方法名[%s]+参数[%s]:没有匹配的方法",methodName, JSON.toJSON(params)));
            }else {
                Method method = aClass.getMethod(methodName);
                Assert.notNull(method,String.format("方法名[%s]:没有匹配的方法",methodName));
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("方法名[]+参数[]:没有匹配的方法",methodName,JSON.toJSON(params)));
        }

        // 记录回调方法
        String callbackObj = null != callbackMethod ? ObjectUtil.objectToString(callbackMethod) : null;

        // 参数保存
        StringBuilder builder = new StringBuilder();
        if(null != params){
            int length = params.length;
            for(int i = 0;i<length;i++){
                builder.append(ObjectUtil.objectToString(params[i]));
                if(i != length-1){
                    builder.append(DELIMITER);
                }
            }
        }


        // 记录重推参数
        LocalDateTime date = LocalDateTime.now();
        RePush rePush = RePush.builder()
                .interfaceName(interfaceName)
                .className(className)
                .methodName(methodName)
                .callbackObj(callbackObj)
                .params(builder.toString())
                .status(status)
                .createTime(date)
                .updateTime(date)
                .build();

        // 保存重推的参数
        //rePushMapper.insert(rePush);
    }

    /**
     * 重推 (后期建立定时任务,定时执行)
     */
    @Override
    public void rePush() throws Exception {
        // 查询要重推的数据
        List<RePush> rePushes = queryRePushData();
        if(CollectionUtils.isEmpty(rePushes)) return;

        for(RePush rePush : rePushes){
            if(Objects.equals(STATUS_SUCCESS,rePush.getStatus())) return;
            try {
                rePushHandler(rePush);
            } catch (Exception e) {
                log.error("重推记录id[{}]异常:{}=={}",rePush.getRePushId(),e.getMessage(),Arrays.toString(e.getStackTrace()),e);
            }
        }
    }

    /**
     * 执行重推
     * InvocationTargetException
     * @param rePush
     * @throws ClassNotFoundException
     * @throws InstantiationException
     * @throws IllegalAccessException
     *
     */
    public void rePushHandler(RePush rePush) throws Exception {
        // 待重推的类
        Class<?> aClass = Class.forName(rePush.getClassName());

        // 重推方法
        Method method = Arrays.stream(aClass.getDeclaredMethods())
                .filter(methodTemp -> Objects.equals(methodTemp.getName(), rePush.getMethodName()))
                .findAny()
                .orElseThrow(() -> new RuntimeException("获取方法失败"));
        method.setAccessible(true);

        // 创建实例
        Object instance = aClass.newInstance();

        // 方法执行结果
        Object result;

        // 重推参数
        String params = rePush.getParams();
        if(StringUtils.isEmpty(params)){
            result = method.invoke(instance);
        }else {
            // 解析参数执行方法
            String[] objStrs = params.split(DELIMITER);
            int length = objStrs.length;
            Object[] objParams = new Object[length];
            for(int i=0;i<length;i++){
                objParams[i] = ObjectUtil.stringToObject(objStrs[i]);
            }
            result = method.invoke(instance,objParams);
        }

        // 请求回调方法
        String callbackObj = rePush.getCallbackObj();

        // 回调方法执行状态
        boolean resultStatus = true;
        if(StringUtils.isNotEmpty(callbackObj)){
            // 回调方法执行
            Predicate predicate = (Predicate) ObjectUtil.stringToObject(callbackObj);
            resultStatus = predicate.test(result);
        }

        // 更新重推记录
        rePush.setPushNum(rePush.getPushNum()+1); // 重推次数+1
        rePush.setUpdateTime(LocalDateTime.now());
        if(resultStatus){
            rePush.setStatus(STATUS_SUCCESS);
        }
        //rePushMapper.updateByPrimaryKey(rePush);
    }

}